"""Build script."""

from setuptools import Extension, find_packages
from setuptools.command.build_ext import build_ext
from setuptools.errors import CCompilerError, ExecError, PlatformError

monty_hall_modules = [
    # 最后一个必须是c模块定义的模块名
    Extension("example_c_extension.example", sources=["example_libc/example_do.c"]),
    Extension("example_c_extension.math.cmath", sources=["example_libc/example_add.c"]),
]


class BuildFailed(Exception):
    pass


class ExtBuilder(build_ext):
    def run(self):
        try:
            build_ext.run(self)
        except (PlatformError, FileNotFoundError):
            pass

    def build_extension(self, ext):
        try:
            build_ext.build_extension(self, ext)
        except (CCompilerError, ExecError, PlatformError, ValueError):
            pass


def build(setup_kwargs: dict):
    setup_kwargs.update({
        "ext_modules": monty_hall_modules,
        "packages": find_packages(),
        # 将编译结果复制回本模块，方便测试
        "script_args": ["build_ext", "--inplace"],
    })
